package org.atovio.coolexam.service.impl;

import org.atovio.coolexam.entity.Question;
import org.atovio.coolexam.exception.ServiceException;
import org.atovio.coolexam.mapper.QuestionMapper;
import org.atovio.coolexam.mapper.QuestionOptionsMapper;
import org.atovio.coolexam.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
@Transactional
public class QuestionServiceImpl implements QuestionService {

    private final QuestionMapper questionMapper;
    private final QuestionOptionsMapper questionOptionsMapper;

    @Autowired
    public QuestionServiceImpl(QuestionMapper questionMapper, QuestionOptionsMapper questionOptionsMapper) {
        this.questionMapper = questionMapper;
        this.questionOptionsMapper = questionOptionsMapper;
    }

    @Override
    public int getCount(Map<String, Object> criteria) {
        return questionMapper.selectCountSelective(criteria);
    }

    @Override
    public Question add(Question question) {
        questionMapper.insert(question);
        return questionMapper.selectByContent(question.getContent());
    }

    @Override
    public List<Question> getAll() {
        return questionMapper.selectAll();
    }

    @Override
    public Question getById(int id) {
        return questionMapper.selectById(id);
    }

    @Override
    public List<Question> getByQuestionTypeOnRandom(int questionType) {
        return questionMapper.selectByQuestionTypeOnRandom(questionType);
    }

    @Override
    public List<Question> getSelective(Map<String, Object> criteria) {
        return questionMapper.selectSelective(criteria);
    }

    @Override
    public void deleteById(int id) {
        int count = questionMapper.deleteById(id);
        if (count != 1)
            throw new ServiceException("数据库内部错误");
        questionOptionsMapper.deleteByQuestionId(id);
    }
}
